<?php
	class DBConnection
	{
		private $_mysqli = null;
		
		public function Connect()
		{
			$this->_mysqli = new \mysqli(DBSettings::DBHOST(), DBSettings::DBUSER(), DBSettings::DBPASSWORD(), DBSettings::DATABASE());
			
			$this->_mysqli->set_charset("utf8");
			
			if ($this->_mysqli->connect_errno)
			{
				Log::LogError("A fatal error occured.", "Connection Failed: " . $this->_mysqli->connect_error);
				return false;
			}
			return true;	
		}	
		
		// Closes the mysql connection.
		public function Close()
		{
			$this->_mysqli->close();	
		}	
		
		// Prepares a sql-query and returns a statment or throws and exception.
		public function Prepare($sql)
		{
			$stmt = $this->_mysqli->prepare($sql);
			
			if ($stmt === false)
			{
				Log::LogError("A fatal error occured.", "Prepare of " . $sql . " failed " . $this->_mysqli->error);
			}	
			return $stmt;
		}
		
		// Executs the statment and returns an array with the result.
		public function RunAndFetchObjects(\mysqli_stmt $a_stmt, $a_className, $a_nameOfPrimaryKey)
		{
			$ret = array();
			
			$a_stmt->execute();
			
			$result = $a_stmt->get_result();
			
			while ($object = $result->fetch_object($a_className))
			{
				$ret[$object->$a_nameOfPrimaryKey] = $object;	
			}
			
			$a_stmt->close();
			
			return $ret;
		}
	}	